<?php

class PostController extends Controller {
    /**
     * @var string the default layout for the views. Defaults to 'column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='post';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;


    /**
     * Displays a particular model.
     */
    public function actionView() {
        $model=new Coment('captch');

        if(isset($_POST['Coment'])) {
            $model->attributes=$_POST['Coment'];
            $model->id_name='post';
            $model->id_post=$_GET['id'];
            $model->autor=Yii::app()->user->name;
            if($model->save())
                $this->redirect(array('view','id'=>$_GET['id']));
        }

        $criteria=new CDbCriteria;
        $criteria->condition='id_name=:id_name AND id_post=:id_post';
        $criteria->params=array(':id_name'=>'post', ':id_post'=>$_GET['id']);

        $dataProvider=new CActiveDataProvider('Coment',array(
                        'criteria'=>$criteria,
        ));

        $this->render('view',array(
                'model'=>$this->loadModel(),
                'dataProvider'=>$dataProvider,
                'coment_model'=>$model,
        ));
    }


    /**
     * Lists all models.
     */
    public function actionIndex() {
        $criteria = new CDbCriteria(array('order'=>'id_post DESC','condition'=>'visible=1'));
        if(isset($_GET['tag'])) {
            $criteria->compare('tags',$_GET['tag'],true);
        }
        $dataProvider=new CActiveDataProvider('Post',array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                                'pageSize'=>Config::model()->find('conf_name=:name', array(':name'=>'pagination'))->conf_value,
                        ),
        ));


        $this->render('index',array(
                'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=Post::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            if($this->_model->visible == 0)
                throw new CHttpException(404,'Статья не найдена');
        }
        return $this->_model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if(isset($_POST['ajax']) && $_POST['ajax']==='post-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
